package com.sprite.framework.entity.script;

import java.util.HashMap;
import java.util.Map;

import com.sprite.framework.entity.DataScriptStatement;
import com.sprite.framework.entity.EntityCondition;
import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.EntityScript;
import com.sprite.framework.entity.model.ModelEntity;
import com.sprite.framework.entity.model.ModelEntityUtil;
import com.sprite.framework.entity.model.ModelEntityView;
import com.sprite.utils.UtilString;

/**
 * 更新脚本
 * @author Jack
 *
 */
public final class EntityUpdateScript implements EntityScript{
	

	private String entityName;
	
	/**
	 * field collection
	 */
	private Map<String, Object> fieldsToUpdate = new HashMap<String, Object>();

	private EntityCondition whereCondition;			// 查询条件

	
	public EntityUpdateScript(String entityName) {
		this.entityName = entityName;
	}

	protected EntityUpdateScript() {
		
	}

	public void setWhereCondition(EntityCondition whereCondition){
		this.whereCondition = whereCondition;
	}

	public void makeStatement(DataScriptStatement statement, ModelEntityView modelViewEntity) throws EntityException{
		initModelViewEntity(modelViewEntity);
		
		ModelEntity modelEntity = ModelEntityUtil.getModelEntity(entityName);
		
		statement.append(UtilString.place("UPDATE {} SET ", modelEntity.getTableName()));
		
		int lg = fieldsToUpdate.size();
		for(Map.Entry<String, Object> entry : fieldsToUpdate.entrySet()) {
			statement.append(modelEntity.getModelField(entry.getKey()).getColName()).append("=?");
			statement.addParam(entry.getValue());
			if(lg > 1) {
				statement.append(",");
			}
			lg--;
		}
		
		statement.append(" WHERE ");
		whereCondition.makeScript(statement, modelEntity);
	}

	public void addFields(Map<String, Object> fields) {
		fieldsToUpdate.putAll(fields);
	}
	
	private void initModelViewEntity(ModelEntityView modelViewEntity) throws EntityException{
		if(modelViewEntity == null){
			return ;
		}
	}

	@Override
	public DataScriptStatement getStatement() {
		DataScriptStatement statement = new DataScriptStatement();
		makeStatement(statement, null);
		return statement;
	}

}
